﻿<%@ WebHandler Language="C#" Class="SpecialReportUnlimitedHandler" %>
using System;
using System.Web;
using BusinessRule.DTO;
using System.Web.SessionState;
using DatabaseAccess.DBUtility;
using System.Data.OracleClient;
using System.Data;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Collections;
using Newtonsoft.Json;
using BusinessRule.Business;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;
using System.Net;

//Description: 批次特殊过程无限制处理程序
//Copyright (c) : 通力凯顿（北京）系统集成有限公司
//Writer:zhangrj
//create Date:2025-04-15
public class SpecialReportUnlimitedHandler : IHttpHandler, IRequiresSessionState
{

    CurrentUserInfo m_UserInfo;
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            var action = context.Request["action"].ToString();
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            if (m_UserInfo == null)
            {
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "登录过期，请重新登录" }));
                return;
            }
            if (!m_UserInfo.Roles.Contains("检验室室主任"))
            {
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "当前用户无权限！" }));
                return;
            }
            switch (action)
            {
                case "GetContainerSpecialSpec": //获取批次的特殊过程工序
                    GetContainerSpecialSpec(context);
                    break;
                case "SaveSpecialUnlimitedDatas": //保存特殊过程工序到无限制名单
                    SaveSpecialUnlimitedDatas(context);
                    break;
                case "GetSpecialUnLimitDatas": //获取无限制名单
                    GetSpecialUnLimitDatas(context);
                    break;
                default:
                    context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "不存在该功能" }));
                    break;
            }
        }
        catch (Exception ex)
        {
            uMESProcessResult result = new uMESProcessResult();
            result.Result = false;
            result.Message = ex.Message;
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }

    /// <summary>
    /// 获取批次的特殊过程工序
    /// </summary>
    /// <param name="context"></param>
    public void GetContainerSpecialSpec(HttpContext context)
    {
        string containerName = context.Request["containerName"].ToString();
        if (string.IsNullOrWhiteSpace(containerName))
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "请输入批次名进行查询！" }));
            return;
        }
        StringBuilder sql = new StringBuilder();
        sql.AppendFormat(@"SELECT c.containername,c.containerid,c.originalfactoryid,ws.workflowstepname,ws.workflowstepid,c.workflowname || ':' || c.workflowrevision workflowinfo,
                        DECODE(sr.specialreportunlimitedinfoid,NULL,'否','是') isUnlimitname
                        FROM containercurrentinfo c
                        LEFT JOIN workflow w ON w.workflowid = c.workflowid
                        LEFT JOIN workflowstep ws ON ws.workflowstepid = c.workflowstepid
                        LEFT JOIN specbase sb ON sb.specbaseid = ws.specbaseid
                        LEFT JOIN spec s ON s.specid = NVL(sb.revofrcdid, ws.specid)
                        LEFT JOIN specialreportunlimitedinfo sr ON sr.containerid = c.containerid AND sr.workflowstepid = ws.workflowstepid
                        WHERE c.containername = '{0}' AND c.containerstatus  = 1 AND s.isspotcheck = 1
                        ORDER BY ws.sequence", containerName);
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        result.DBTable = DatabaseHelper.Query_ReturnDatTable(sql.ToString());
        if (result.DBTable.Rows.Count == 0)
        {
            result.Result = false; result.Message = "批次在制工艺下无特殊过程工序！";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        if (result.DBTable.Rows[0]["originalfactoryid"].ToString() != m_UserInfo.FactoryID)
        {
            result.Result = false; result.Message = "批次不属于当前用户分厂！";
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 获取无限制名单
    /// </summary>
    /// <param name="context"></param>
    public void GetSpecialUnLimitDatas(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        StringBuilder sql = new StringBuilder();
        sql.AppendLine(@"SELECT c.containername,c.workflowname || ':' || c.workflowrevision workflowinfo,
                        ws.workflowstepname,sr.createtime,e.fullname,sr.remark
                        FROM specialreportunlimitedinfo sr
                        LEFT JOIN containercurrentinfo c ON c.containerid = sr.containerid
                        LEFT JOIN workflowstep ws ON ws.workflowstepid = sr.workflowstepid
                        LEFT JOIN workflow w ON w.workflowid = ws.workflowid
                        LEFT JOIN Workflowbase wb ON wb.workflowbaseid = w.workflowbaseid
                        LEFT JOIN employee e ON e.employeeid = sr.createby
                        WHERE sr.status = 0 AND c.containerstatus = 1
                        ORDER BY sr.containerid,ws.sequence");
        //if (!string.IsNullOrWhiteSpace(context.Request["startDate"].ToString()))
        //{
        //    DateTime startDate = DateTime.Parse(context.Request["startDate"].ToString() + " 00:00:00");
        //    sql.AppendFormat(" AND a.createtime >= to_date('{0}','yyyy-mm-dd hh24:mi:ss')", startDate);
        //}
        //if (!string.IsNullOrWhiteSpace(context.Request["endDate"].ToString()))
        //{
        //    DateTime endDate = DateTime.Parse(context.Request["endDate"].ToString() + " 23:59:59");
        //    sql.AppendFormat(" AND a.createtime <= to_date('{0}','yyyy-mm-dd hh24:mi:ss')", endDate);
        //}
        //sql.AppendLine(" ORDER BY a.createtime desc,c.containerid,ws.sequence");
        uMESPagingDataDTO pageDto = new uMESPagingDataDTO();
        pageDto.CurrentPageIndex = int.Parse(context.Request["pageIndex"].ToString());
        pageDto.PageSize = int.Parse(context.Request["pageSize"].ToString());
        pageDto.strSQL = sql.ToString();
        result = DatabaseHelper.RunProcedureForPage(pageDto);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 保存特殊过程工序到无限制名单
    /// </summary>
    /// <param name="context"></param>
    public void SaveSpecialUnlimitedDatas(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        DataTable dtSpec = JsonConvert.DeserializeObject<DataTable>(context.Request["params"].ToString());
        ArrayList sqlList = new ArrayList();
        StringBuilder sqlBd = new StringBuilder();
        foreach (DataRow drSpec in dtSpec.Rows)
        {
            string sql = string.Format("SELECT 1 FROM specialreportunlimitedinfo sr WHERE sr.containerid = '{0}' AND sr.workflowstepid = '{1}' AND sr.status = 0 ", drSpec["containerid"].ToString(), drSpec["workflowstepid"].ToString());
            if (DatabaseHelper.GetSingle(sql) != null)
            {
                result.Result = false; result.Message = string.Format("批次：{0}的工序：{1}已添加到无限制名单", drSpec["containername"].ToString(), drSpec["workflowstepname"].ToString());
                break;
            }
            sqlBd.AppendLine(@"INSERT INTO specialreportunlimitedinfo(specialreportunlimitedinfoid,containerid,workflowstepid,Createtime,Createby,Status,Remark) VALUES(");
            sqlBd.AppendFormat("'{0}',", Guid.NewGuid().ToString());//主键ID
            sqlBd.AppendFormat("'{0}',", drSpec["containerid"].ToString());//批次ID
            sqlBd.AppendFormat("'{0}',", drSpec["workflowstepid"].ToString());//工序ID
            sqlBd.AppendLine("sysdate,");//创建时间
            sqlBd.AppendFormat("'{0}',", m_UserInfo.EmployeeID);//创建人
            sqlBd.AppendFormat("0,'操作电脑IP：{0}')", context.Request.UserHostAddress);//默认为有效，备注操作人IP
            sqlList.Add(sqlBd.ToString());
        }
        if (result.Result)
        {
            DatabaseHelper.ExecuteSqlTran(sqlList);
            result.Message = "保存成功";
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}